<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                        <!-- 搜索表单部分 -->
                        <el-form-item label="用户昵称" prop="nikeName">
                            <el-input
                                    v-model="queryParams.nikeName"
                                    placeholder="请输入用户昵称"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="对话标题" prop="conversationTitle">
                            <el-input
                                    v-model="queryParams.conversationTitle"
                                    placeholder="请输入对话标题"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <!-- <el-form-item label="用户ID" prop="userId">
                            <el-input
                                    v-model="queryParams.userId"
                                    placeholder="请输入用户ID"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="会话ID" prop="conversationId">
                            <el-input
                                    v-model="queryParams.conversationId"
                                    placeholder="请输入会话ID"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item> -->
                        <el-form-item label="收藏时间" prop="createdTime">
                            <el-date-picker clearable
                                            v-model="queryParams.createdTime"
                                            type="date"
                                            value-format="YYYY-MM-DD"
                                            placeholder="请选择收藏时间">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="更新时间" prop="updatedTime">
                            <el-date-picker clearable
                                            v-model="queryParams.updatedTime"
                                            type="date"
                                            value-format="YYYY-MM-DD"
                                            placeholder="请选择状态更新时间">
                            </el-date-picker>
                        </el-form-item>
                        <!-- <el-form-item label="评价分数" prop="starRating">
                            <el-input
                                    v-model="queryParams.starRating"
                                    placeholder="请输入评价分数"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item> -->
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <!-- <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['teenage:userFavorite:add']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['teenage:userFavorite:edit']"
                >修改</el-button>
            </el-col> -->
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['teenage:userFavorite:remove']"
                >删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['teenage:userFavorite:export']"
                >导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userFavoriteList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="用户昵称" align="center" prop="nikeName" />
            <el-table-column label="对话标题" align="center" prop="conversationTitle" />
                    <!-- <el-table-column label="收藏记录唯一标识" align="center" prop="id" />
                    <el-table-column label="用户ID" align="center" prop="userId" />
                    <el-table-column label="会话ID" align="center" prop="conversationId" /> -->
                    <el-table-column label="收藏状态" align="center" prop="isFavorite">
                        <template #default="scope">
                            <el-tag :type="scope.row.isFavorite == 1 || scope.row.isFavorite === true ? 'primary' : 'info'" size="small">
                                {{ scope.row.isFavorite == 1 || scope.row.isFavorite === true ? '是' : '否' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="收藏时间" align="center" prop="createdTime" width="180">
                        <template #default="scope">
                            <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态更新时间" align="center" prop="updatedTime" width="180">
                        <template #default="scope">
                            <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="用户反馈" align="center">
                        <template #default="scope">
                            <el-button link type="primary" @click="openFeedbackDetail(scope.row)">查看详情</el-button>
                        </template>
                    </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['teenage:userFavorite:edit']">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['teenage:userFavorite:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 用户反馈详情弹框 -->
        <el-dialog title="用户反馈" v-model="feedbackDialogVisible" width="500px" append-to-body>
            <el-descriptions :column="1" border>
                <el-descriptions-item label="评价分数">
                    <el-rate
                        :max="5"
                        :model-value="(Number(feedbackDetail.starRating) || 0) / 2"
                        disabled
                        allow-half
                        :colors="['#ff9900', '#ff9900', '#ff9900']"
                        :void-color="'#e6e6e6'"
                        :disabled-void-color="'#e6e6e6'"
                    />
                    <span style="margin-left: 8px;">{{ Number(feedbackDetail.starRating) || 0 }}分</span>
                </el-descriptions-item>
                <el-descriptions-item label="用户评价">
                    <span>{{ feedbackDetail.userComment || '-' }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="反馈标签">
                    <span>{{ formatFeedbackTags(feedbackDetail.feedbackTags) }}</span>
                </el-descriptions-item>
            </el-descriptions>
        </el-dialog>

        <!-- 添加或修改用户会话收藏对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="userFavoriteRef" :model="form" :rules="rules" label-width="80px">
                                <el-form-item label="用户ID" prop="userId">
                                    <el-input v-model="form.userId" placeholder="请输入用户ID" />
                                </el-form-item>
                                <el-form-item label="会话ID" prop="conversationId">
                                    <el-input v-model="form.conversationId" placeholder="请输入会话ID" />
                                </el-form-item>
                                <el-form-item label="收藏时间" prop="createdTime">
                                    <el-date-picker clearable
                                                    v-model="form.createdTime"
                                                    type="date"
                                                    value-format="YYYY-MM-DD"
                                                    placeholder="请选择收藏时间">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="状态更新时间" prop="updatedTime">
                                    <el-date-picker clearable
                                                    v-model="form.updatedTime"
                                                    type="date"
                                                    value-format="YYYY-MM-DD"
                                                    placeholder="请选择状态更新时间">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="评价分数" prop="starRating">
                                    <el-input v-model="form.starRating" placeholder="请输入评价分数" />
                                </el-form-item>
                                <el-form-item label="反馈标签" prop="feedbackTags">
                                    <el-input v-model="form.feedbackTags" placeholder="请输入反馈标签" />
                                </el-form-item>
                                <el-form-item label="用户评价" prop="userComment">
                                    <el-input v-model="form.userComment" placeholder="请输入用户评价" />
                                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="UserFavorite">
    import { listUserFavorite, getUserFavorite, delUserFavorite, addUserFavorite, updateUserFavorite } from "@/api/teenage/userFavorite";

    const { proxy } = getCurrentInstance();

    const userFavoriteList = ref([]);
    const open = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const title = ref("");
    const feedbackDialogVisible = ref(false);
    const feedbackDetail = ref({});

    const data = reactive({
        form: {},
        // queryParams对象
        queryParams: {
            pageNum: 1,
            pageSize: 10,
            userId: null,
            conversationId: null,
            isFavorite: null,
            createdTime: null,
            updatedTime: null,
            starRating: null,
            feedbackTags: null,
            nikeName: null,
            conversationTitle: null,
        },
        rules: {
        }
    });

    const { queryParams, form, rules } = toRefs(data);

    /** 查询用户会话收藏列表 */
    function getList() {
        loading.value = true;
        const toMidnight = (dateStr) => {
            if (!dateStr) return dateStr;
            if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
                return `${dateStr} 00:00:00`;
            }
            return dateStr;
        };
        const query = {
            ...queryParams.value,
            // 后端按天匹配，传 createdDate/updatedDate 即可
            createdDate: queryParams.value.createdTime || null,
            updatedDate: queryParams.value.updatedTime || null,
        };
        // 移除会触发后端绑定错误的旧参数
        delete query.createdTime;
        delete query.updatedTime;
        listUserFavorite(query).then(response => {
            userFavoriteList.value = response.rows;
            total.value = response.total;
            loading.value = false;
        });
    }

    // 取消按钮
    function cancel() {
        open.value = false;
        reset();
    }

    // 表单重置
    function reset() {
        // form对象
        form.value = {
            id: null,
            userId: null,
            conversationId: null,
            isFavorite: null,
            createdTime: null,
            updatedTime: null,
            starRating: null,
            feedbackTags: null,
            userComment: null,
            nikeName: null,
            conversationTitle: null
        };
        proxy.resetForm("userFavoriteRef");
    }

    /** 搜索按钮操作 */
    function handleQuery() {
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    function resetQuery() {
        proxy.resetForm("queryRef");
        handleQuery();
    }

    // 多选框选中数据
    function handleSelectionChange(selection) {
        ids.value = selection.map(item => item.id);
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    }

    /** 新增按钮操作 */
    function handleAdd() {
        reset();
        open.value = true;
        title.value = "添加用户会话收藏";
    }

    /** 修改按钮操作 */
    function handleUpdate(row) {
        reset();
        const _id = row.id || ids.value
        getUserFavorite(_id).then(response => {
            form.value = response.data;
            open.value = true;
            title.value = "修改用户会话收藏";
        });
    }

    // 打开用户反馈详情弹框
    function openFeedbackDetail(row) {
        feedbackDetail.value = {
            starRating: row.starRating,
            userComment: row.userComment,
            feedbackTags: row.feedbackTags
        };
        feedbackDialogVisible.value = true;
    }

    /** 提交按钮 */
    function submitForm() {
        proxy.$refs["userFavoriteRef"].validate(valid => {
            if (valid) {
                // 调试：打印提交的数据
                console.log('提交的表单数据:', form.value);
                console.log('feedbackTags类型:', typeof form.value.feedbackTags);
                console.log('feedbackTags值:', form.value.feedbackTags);
                
                if (form.value.id != null) {
                    updateUserFavorite(form.value).then(response => {
                        proxy.$modal.msgSuccess("修改成功");
                        open.value = false;
                        getList();
                    });
                } else {
                    addUserFavorite(form.value).then(response => {
                        proxy.$modal.msgSuccess("新增成功");
                        open.value = false;
                        getList();
                    });
                }
            }
        });
    }

    /** 删除按钮操作 */
    function handleDelete(row) {
        const _ids = row.id || ids.value;
        proxy.$modal.confirm('是否确认删除用户会话收藏编号为"' + _ids + '"的数据项？').then(function() {
            return delUserFavorite(_ids);
        }).then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    }

    /** 导出按钮操作 */
    function handleExport() {
        proxy.download('teenage/userFavorite/export', {
            ...queryParams.value
        }, `userFavorite_${new Date().getTime()}.xlsx`)
    }

    /** 格式化反馈标签 */
    function formatFeedbackTags(tags) {
        if (!tags || tags.toString().trim() === '') return '-';
        
        const tagMap = {
            '1': '答案准确',
            '2': '内容完善', 
            '3': '易于理解',
            '4': '答案不准确',
            '5': '流程复杂',
            '6': '信息虚假'
        };
        
        const tagArray = tags.toString().split(',').filter(tag => tag.trim() !== '');
        if (tagArray.length === 0) return '-';
        
        return tagArray.map(tag => tagMap[tag.trim()] || tag.trim()).join('，');
    }

    getList();
</script>